﻿var Server = function (rack) {
	var self = this;
	this.rack = rack;
	
	this.Load();
	
	this.EnterEditMode = function() {
		/*$('#rack_info .td_edit').show().each(function(index, item) {
			$(item).click(function() {
				if ($(item).parent().data('data')) self.Edit($(item).parent());
				else self.Add($(item).parent().data('unit'));
			});
		});
		$('#rack_info .td_remove').show().each(function(index, item) {
			$(item).click(function() {
				if ($(item).parent().data('data')) self.Remove($(item).parent());
				else return false;
			});
		});*/
		$('#rack_info .td_edit').show();
		$('#rack_info .td_add').show();
		$('#rack_info .td_remove').show();
		$('#rack_info .td_empty').show();
		$('#rack_info .td_lock').show();
		$('#rack_info .td_locked').show();
		self.ResizeTable();
		var btn = $('#servers_add_icon');
		if (btn.length == 0) {
			btn = $("<a href='#' style='float:right; padding-top:10px;padding-bottom:10px;'></a>")
			.button({ icons: { primary: "ui-icon-plus" }, text: false }).attr('id', 'servers_add_icon')
			.insertAfter($('#servers_edit_mode_icon'));
		} else btn.unbind('click').show();
		btn.click(function() {
			self.Add();
		});
		$('#servers_edit_mode_icon').button('option', 'icons', { primary: "ui-icon-check" }).unbind('click').click(function() {
			self.LeaveEditMode();
		});
	};
	
	this.ReloadTable = function() {
		var self = this;
		var call = new ServerCall();
		call.Load(self.rack.id, null, function(data) {
			self.ShowServers(data);
			self.EnterEditMode();
		});
	};
	
	this.LeaveEditMode = function() {
		$('#servers_add_icon').unbind('click').hide();
		$('#rack_info .td_empty').hide();
		$('#servers_edit_mode_icon').button('option', 'icons', { primary: "ui-icon-pencil" }).unbind('click').click(function() {
			self.EnterEditMode();
		});
		$('#rack_info .td_edit').hide();
		$('#rack_info .td_remove').hide();
		$('#rack_info .td_add').hide();
		$('#rack_info .td_lock').hide();
		$('#rack_info .td_locked').hide();
		self.ResizeTable();
	};
	
	this.FindServer = function (servers, unit) {
        var to_delete = -1;
        var found = null;
        for (var i in servers) {
            var server = servers[i];
            //console.log(server);
			if (server.units.indexOf('-') > -1) {
				var units = server.units.split('-');
				if (parseInt(units[1]) == parseInt(unit)) {
					return server;
				}
			} else if (parseInt(server.units) == unit) return server;
        }
        /*if (to_delete > -1) {
            servers.splice(to_delete, 1);
        }*/
        return found;
    };
	
	this.ResizeTable = function() {
		if ($('#datatable1').actual('outerWidth') < 350) {
            $('#datatable1').width(350);
        }
        var w = $('#datatable1').actual('outerWidth') + 30;
        //w = Math.floor(w + w * 0.25);
		$("#rack_info").dialog('option', 'minWidth', w);
	}
	
	this.Hint = function(server) {
		return title = 'Vendor: ' + server.vendor + "\r\n" + 'Type: ' + (server.type ? server.type : '') + "\r\n" + 'S/N: ' + server.sn + "\r\n" + 'I/N: ' + (server['in'] ? server['in'] : '') + "\r\nResponsible: " + (server.responsible ? server.responsible : '');
	}
	
	this.ShowServers = function(servers) {
		var self = this;
        var d = $("#rack_info").attr('title', '').empty();
        var table = $('<table cellspacing="0" cellpadding="0" class="table" id="datatable1"></table>').appendTo(d);

        for (var i = rack.units; i > 0; i--) {
            var server = self.FindServer(servers, i);
            if (server != null) {
				if (server.name == 'reserved') {
					$('<tr><td class="left_td locked">U' + i + '</td><td class="simple locked">&nbsp;</td><td class="simple locked">&nbsp;</td><td class="simple locked">&nbsp;</td><td class="right_td locked">&nbsp;</td><td class="td_empty">&nbsp;</td><td class="td_locked" style="display:none">&nbsp;</td></tr>').appendTo(table).data('unit', i);
				} else {
					var tr = $('<tr></tr>').appendTo(table);
					tr.data('data', server);
					var pstate_style = '';
					var color = 'white';
					if (server.pstate == 'False') color = '#999999';
					else if (server.color) color = server.color;
					else if (server.vcolor) color = server.vcolor;
					var ips = server.srvip.join('<br />');
					
					var unit = 0;
					var units = 0;
					if (server.units.indexOf('-') > -1) {
						var items = server.units.split('-');
						unit = parseInt(items[1]);
						units = parseInt(items[1]) - parseInt(items[0]) + 1;
					} else {
						unit = parseInt(server.units);
						units = 1;
					}
					var mgmtip = '';
					if (server.mgmtip) {
						var items = server.mgmtip.split('.');
						items.splice(0, 2);
						mgmtip = items.join('.');
					}
					console.log('server: ' + server.name +  ', units: ' + server.units + ', ' + unit + ' - ' + units);
					var span = (units > 1) ? ' rowspan="' + units + '"' : '';
					var style = ' style="background-color:' + color + ';color:' + ForeColor(color) + '"';
					$('<td class="left_td full_bold"' + style + '>U' + i + '</td>').appendTo(tr);
					$('<td class="top_bold bottom_bold"' + style + span + ' title="' + self.Hint(server) + '">' + server.model + '</td>').appendTo(tr).tooltip();
					$('<td class="top_bold bottom_bold"' + style + span + ' title="' + server.notes + '">' + server.name + '</td>').appendTo(tr).tooltip();
					$('<td class="top_bold bottom_bold"' + style + span + '>' + ips + '</td>').appendTo(tr);
					$('<td class="full_bold"' + style + span + '>' + mgmtip + '</td><td class="td_edit"' + span + '>&nbsp;</td><td class="td_remove"' + span + '>&nbsp;</td>').appendTo(tr);
					if (units > 1) {
						for (var ii = 1; ii < units; ii++) {
							$('<tr><td class="full_bold"' + style + '>U' + (parseInt(i) - parseInt(ii)) + '</td></tr>').appendTo(table);
						}
						i -= parseInt(units) - 1;
					}
				}
            } else {
                $('<tr><td class="left_td">U' + i + '</td><td class="simple">&nbsp;</td><td class="simple">&nbsp;</td><td class="simple">&nbsp;</td><td class="right_td">&nbsp;</td><td class="td_add">&nbsp;</td><td class="td_lock" style="display:none">&nbsp;</td></tr>').appendTo(table).data('unit', i);
            }
        }
        $('#datatable1 td').tooltip();
		$("<a href='#'></a>")
			.button({ icons: { primary: "ui-icon-pencil" }, text: false }).attr('id', 'edit_server')
			.appendTo($('.td_edit'));
		$("<a href='#'></a>")
			.button({ icons: { primary: "ui-icon-plus" }, text: false }).attr('id', 'edit_server')
			.appendTo($('.td_add'));
		$("<a href='#'></a>")
			.button({ icons: { primary: "ui-icon-close" }, text: false }).attr('id', 'remove_server')
			.appendTo($('.td_remove'));
		$("<a href='#' title='Lock unit'></a>")
			.button({ icons: { primary: "ui-icon-locked" }, text: false }).attr('id', 'lock_unit')
			.appendTo($('.td_lock'));
		$("<a href='#' title='Unlock unit'></a>")
			.button({ icons: { primary: "ui-icon-unlocked" }, text: false }).attr('id', 'unlock_unit')
			.appendTo($('.td_locked'));
		d.show().dialog({title: rack.name, modal: true, minHeight: 400, close: function (event, ui) {
            d.dialog('destroy').removeAttr('style').empty();
        }});
		$('#rack_info .td_edit, .td_add').each(function(index, item) {
			$(item).click(function() {
				if ($(item).parent().data('data')) self.Edit($(item).parent());
				else self.Add($(item).parent().data('unit'));
			});
		});
		$('#rack_info .td_remove').each(function(index, item) {
			$(item).click(function() {
				if ($(item).parent().data('data')) self.Remove($(item).parent());
				else return false;
			});
		});
		$('#rack_info .td_lock').each(function(index, item) {
			$(item).click(function() {
				self.LockUnit($(item).parent().data('unit'));
			});
		});
		$('#rack_info .td_locked').each(function(index, item) {
			$(item).click(function() {
				self.UnlockUnit($(item).parent().data('unit'));
			});
		});
		self.ResizeTable();
        return d;
	};
};

Server.prototype.Load = function() {
	var self = this;
	var call = new ServerCall();
	call.Load(self.rack.id, null, function(data) {
		self.ShowServers(data);
		var btn = $('#servers_edit_mode_icon');
		if (btn.length == 0) {
			btn = $("<a href='#' style='float:right; padding-top:10px;padding-bottom:10px;margin-right:15px;'></a>")
			.button({ icons: { primary: "ui-icon-pencil" }, text: false }).attr('id', 'servers_edit_mode_icon')
			.insertBefore($('#rack_info').prev().children('a').first());
		} else btn.unbind('click');
		btn.click(function (e) {
			e.preventDefault();
			self.EnterEditMode();
		});
	});
}
Server.prototype.Remove = function(item) {
	var self = this;
	var call = new ServerCall();
	call.Remove($(item).data('data'), function() {
		$(item).remove();
		self.ReloadTable();
		self.ItemsChanged(-1);
	});
}
Server.prototype.LockUnit = function(unit) {
	var self = this;
	var call = new RackCall();
	call.LockUnit(self.rack.id, unit, function() {
		self.ReloadTable();
		self.ItemsChanged(1);
	});
}
Server.prototype.UnlockUnit = function(unit) {
	var self = this;
	var call = new RackCall();
	call.UnlockUnit(self.rack.id, unit, function() {
		self.ReloadTable();
		self.ItemsChanged(-1);
	});
}
Server.prototype.Add = function(unit) {
	var self = this;
	var form = new ServerForm('add');
	form.Empty();
	form.dc(self.rack.dc_id);
	form.rack(self.rack.id);
	if (unit) form.units(unit);
	form.Show(function(data) {
		self.ReloadTable();
		self.ItemsChanged(1);
	});
	return false;
}

Server.prototype.Edit = function(item) {
	var self = this;
	var form = new ServerForm('edit');
	form.Empty();
	form.Load($(item).data('data'));
	form.Show(function(data) {
		self.ReloadTable();
	});
	return false;
}

// *********************** Server Form ********************************
var ServerForm = function(mode) {
	var self = this;
	this.mode = mode;
	this._vendor = new Vendor($('#form_server_vendor'));
	this._vendor.Load();
	this._dc = new DcSelect($('#form_server_dc'));
	this._dc.Load();
	this._rack = new RackSelect($('#form_server_rack'));
	this._rack.Load();
	$('#form_server_add_ip').unbind('click').button({'icons': { primary: "ui-icon-plus" }}).css({'width': '30px', 'height': '30px', position: 'relative', top: '7px'}).click(function() {
		var br = $('<br class="srv_added" />').appendTo($(this).parent());
		var ip = $('<input type="text" name="ip" class="server_ip srv_added ui-widget ui-widget-content ui-corner-all" />').appendTo($(this).parent());
		var del = $('<a href="#" class="srv_added"></a>').appendTo($(this).parent()).button({'icons': { primary: "ui-icon-minus" }}).css({'width': '30px', 'height': '30px', position: 'relative', top: '7px'}).click(function() {
			br.remove();
			ip.remove();
			del.unbind('click').remove();
			return false;
		});
	});
	this._dc.onChange(function(index, value) {
		console.log(index + ' = ' + value);
		self._rack.Filter(index);
	});
}
ServerForm.prototype.id = function(value) {
	if (typeof value == 'undefined') return $('#form_server_id').val();
	else $('#form_server_id').val(value);
}
ServerForm.prototype.dc = function(value) {
	if (typeof value == 'undefined') return this._dc.SelectedValue();
	else {
		this._dc.Select(value);
		this._rack.Filter(value);
	}
}
ServerForm.prototype.dcName = function() {
	return this._dc.SelectedName();
}
ServerForm.prototype.vendor = function(value) {
	if (typeof value == 'undefined') return this._vendor.SelectedValue();
	else this._vendor.Select(value);
}
ServerForm.prototype.vendorName = function() {
	return this._vendor.SelectedName();
}
ServerForm.prototype.rack = function(value) {
	if (typeof value == 'undefined') return this._rack.SelectedValue();
	else this._rack.Select(value);
}
ServerForm.prototype.rackName = function() {
	return this._rack.SelectedName();
}
ServerForm.prototype.name = function(value) {
	if (typeof value == 'undefined') return $('#form_server_name').val();
	else $('#form_server_name').val(value);
}
ServerForm.prototype.model = function(value) {
	if (typeof value == 'undefined') return $('#form_server_model').val();
	else $('#form_server_model').val(value);
}
ServerForm.prototype.type = function(value) {
	if (typeof value == 'undefined') return $('#form_server_type').val();
	else $('#form_server_type').val(value);
}
ServerForm.prototype.sn = function(value) {
	if (typeof value == 'undefined') return $('#form_server_sn').val();
	else $('#form_server_sn').val(value);
}
ServerForm.prototype["in"] = function(value) {
	if (typeof value == 'undefined') return $('#form_server_in').val();
	else $('#form_server_in').val(value);
}
ServerForm.prototype.pusage = function(value) {
	if (typeof value == 'undefined') return $('#form_server_pusage').val();
	else $('#form_server_pusage').val(value);
}
ServerForm.prototype.pstate = function(value) {
	if (typeof value == 'undefined') return $('#form_server_pstate').attr('checked') ? true : false;
	else {
		value = value.toString().toLowerCase();
		if (value == "on" || value == "true" || value == "1") {
			$('#form_server_pstate').attr('checked', 'checked');
		} else $('#form_server_pstate').removeAttr('checked');
	}
}
ServerForm.prototype.units = function(value) {
	if (typeof value == 'undefined') {
		if ($('#form_server_units2').val()) return $('#form_server_units').val() + '-' + $('#form_server_units2').val();
		else return $('#form_server_units').val();
	} else if (!value) {
		$('#form_server_units').val('');
		$('#form_server_units2').val('');
	} else {
		if (isNaN(value) && value.indexOf('-') > -1) {
			var pair = value.split('-');
			$('#form_server_units').val(pair[0]);
			$('#form_server_units2').val(pair[1]);
		} else {
			$('#form_server_units').val(value);
			$('#form_server_units2').val('');
		}
	}
}
ServerForm.prototype.srvip = function(value) {
	if (typeof value == 'undefined') {
		var ip = [];
		var ips = $('.server_ip');
		for (var i = 0; i < ips.length; i++) {
			ip.unshift($(ips[i]).val());
		}
		return ip;
	}
	else if (value == '' || value.length == 0) {
		$('.srv_added').remove();
		$('#form_server_ip').val('');
	} else {
		if (!$.isArray(value)) value = value.split(',');
		for (var i in value) {
			if (i == 0) $('#form_server_ip').val(value[i]);
			else {
				var ip = value[i];
				var iplist = $('#form_server_add_ip').parent();
				var br = $('<br class="srv_added" />').appendTo(iplist);
				var ip = $('<input type="text" name="ip" class="server_ip srv_added ui-widget ui-widget-content ui-corner-all" />').appendTo(iplist).val(ip);
				var del = $('<a href="#" class="srv_added"></a>').appendTo(iplist).button({'icons': { primary: "ui-icon-minus" }}).css({'width': '30px', 'height': '30px', position: 'relative', top: '7px'}).click(function() {
					br.remove();
					ip.remove();
					del.unbind('click').remove();
				});
			}
		}
	}
}
ServerForm.prototype.mgmtip = function(value) {
	if (typeof value == 'undefined') return $('#form_server_mgmtip').val();
	else $('#form_server_mgmtip').val(value);
}
ServerForm.prototype.notes = function(value) {
	if (typeof value == 'undefined') return $('#form_server_notes').val();
	else $('#form_server_notes').val(value);
}
ServerForm.prototype.color = function(value) {
	if (typeof value == 'undefined') {
		var v = $('#form_server_color').val();
		if (!v) return '';
		else return '#' + v;
	}
	else {
		if (value.indexOf('#') > -1) value = value.substring(1);
		$.jPicker.List[0].color.active.val('hex', value)
		$('#form_server_color').val(value);
	}
}
ServerForm.prototype.responsible = function(value) {
	if (typeof value == 'undefined') return $('#form_server_responsible').val();
	else $('#form_server_responsible').val(value);
}
ServerForm.prototype.Empty = function() {
	this.id('');
	this.dc(0);
	this.rack(0);
	this.vendor(0);
	this.name('');
	this.model('');
	this.type('');
	this.sn('');
	this["in"]('');
	this.pusage('');
	this.pstate(1);
	this.units('');
	this.srvip([]);
	this.mgmtip('');
	this.notes('');
	this.color('');
	this.responsible('');
}
ServerForm.prototype.Load = function(data) {
	this.id(data.id);
	this.dc(data.dc_id);
	this.rack(data.rack_id);
	this.vendor(data.vendor_id);
	this.name(data.name);
	this.model(data.model);
	this.type(data.type);
	this.sn(data.sn);
	this["in"](data["in"]);
	this.pusage(data.pusage);
	this.pstate(data.pstate);
	this.units(data.units);
	this.srvip(data.srvip);
	this.mgmtip(data.mgmtip);
	this.notes(data.notes);
	this.color(data.color);
	this.responsible(data.responsible);
}
ServerForm.prototype.Show = function(callback) {
	var self = this;
	var title = (this.mode == 'add') ? 'Add new server' : 'Edit server';
	$('#server_edit_form').dialog({ title: title, modal: true, width: 'auto', height: 'auto', close: function() { $('.jPicker.Container').hide(); },
		buttons: {
		'Save': function () {
			var vendor = self.vendor();
			if (vendor == 0) {
				Confirm('Are you sure to add vendor ' + self.vendorName() + '?', function() { self._vendor.AddValue(save); });
			} else save();
			function save() {
				var opts = {
					dc_id: self.dc(),
					dc: self.dcName(),
					rack_id: self.rack(),
					rack: self.rackName(),
					name: self.name(),
					vendor_id: self.vendor(),
					vendor: self.vendorName(),
					model: self.model(),
					type: self.type(),
					sn: self.sn(),
					'in': self['in'](),
					pusage: self.pusage(),
					pstate: self.pstate(),
					units: self.units(),
					srvip: self.srvip(),
					mgmtip: self.mgmtip(),
					notes: self.notes(),
					color: self.color(),
					responsible: self.responsible()
				};
				if (self.mode == 'edit') opts.id = self.id();
				var call = new ServerCall();
				call.Save(self.mode, opts, function(data) {
					if (callback) callback(data);
					$('#server_edit_form').dialog('close');
				});
			}
		},
		'Cancel': function () {
			$(this).dialog('close');
		}
	}});
}
// ******************************* Server Full *********************************
var ServerFull = function() {
	var self = this;
	self.Load();
};
ServerFull.prototype.AppendRow = function(item) {
	var self = this;
	var tr = $('<tr><td>' + item.dc + '</td><td>' 
			+ item.rack + '</td><td>'
			+ item.name + '</td><td>' 
			+ item.vendor + '</td><td>'
			+ item.model + '</td><td>'
			+ item.type + '</td><td>'
			+ item.sn + '</td><td>'
			+ item['in'] + '</td><td>'
			+ item.pusage + '</td><td>'
			+ item.pstate + '</td><td>'
			+ item.units + '</td><td style="white-space: normal;">'
			+ item.srvip.join(', ') + '</td><td style="white-space: normal;">'
			+ item.mgmtip + '</td><td style="white-space: normal;">'
			+ item.notes + '</td><td style="white-space: normal;">'
			+ item.responsible + '<td class="server_td_edit">&nbsp;</td><td class="server_td_remove">&nbsp;</td></tr>').appendTo('#tab-servers tbody').data('data', item);
	$("<a href='#'></a>")
	.button({ icons: { primary: "ui-icon-pencil" }, text: false })
	.appendTo(tr.children('.server_td_edit')).click(function() {
		self.Edit($(this).parent().parent());
		return false;
	});
	$("<a href='#'></a>")
	.button({ icons: { primary: "ui-icon-close" }, text: false })
	.appendTo(tr.children('.server_td_remove')).click(function() {
		self.Remove($(this).parent().parent());
		return false;
	});
}
ServerFull.prototype.UpdateRow = function(row, item) {
	var self = this;
	console.log(row);
	console.log(item);
	row.data('data', item).children()
	.first().text(item.dc)
	.next().text(item.rack)
	.next().text(item.name)
	.next().text(item.vendor)
	.next().text(item.model)
	.next().text(item.type)
	.next().text(item.sn)
	.next().text(item['in'])
	.next().text(item.pusage)
	.next().text(item.pstate)
	.next().text(item.units)
	.next().text(item.srvip.join(', '))
	.next().text(item.mgmtip)
	.next().text(item.notes)
	.next().text(item.responsible);
}
ServerFull.prototype.Edit = function(row) {
	var self = this;
	var form = new ServerForm('edit');
	form.Empty();
	form.Load(row.data('data'));
	form.Show(function(data) {
		self.UpdateRow(row, data);
	});
	return false;
}
ServerFull.prototype.Load = function() {
	var self = this;
	$('#tab-servers tbody').empty();
	var call = new ServerCall();
	call.Load(0, function(item) {
		self.AppendRow(item);
	});
	
}
ServerFull.prototype.Add = function() {
	var self = this;
	var form = new ServerForm('add');
	form.Empty();
	form.Show(function(data) {
		self.AppendRow(data);
	});
	return false;
}
ServerFull.prototype.Remove = function(row) {
	console.log(row);
	var call = new ServerCall();
	call.Remove(row.data('data'), function() {
		row.remove();
	});
	return false;
}
// *************************** Server Call *****************************
var ServerCall = function() {
}
ServerCall.prototype.Load = function(rack_id, callback, finish_callback) {
	var self = this;
	var sfx = rack_id ? 'rack_id=' + rack_id : 'mode=full';
	$.getJSON('/call.aspx?source=server&' + sfx, function(data) {
		for (var i = 0; i < data.length; i++) {
			data[i].srvip = data[i].srvip.split(',');
		}
		var cnt = data.length;
		console.log('Total servers: ' + cnt);
		if (cnt == 0 && finish_callback) finish_callback();
		else {
			$.each(data, function(index, item) {
				cnt--;
				if (callback) callback(item);
				if (cnt == 0) {
					if (finish_callback) finish_callback(data);
				}
			});
		}
	});
};

ServerCall.prototype.Save = function(mode, data, callback) {
	data.mode = mode;
	var ips = data.srvip;
	data.srvip = ips.join(',');
	data.source = 'server';
	$.getJSON('/call.aspx', data, function (result) {
		if (result.result == 'RESULT_OK') {
			var item = {
				dc_id: data.dc_id,
				dc: data.dc,
				rack_id: data.rack_id,
				rack: data.rack,
				name: data.name,
				vendor_id: data.vendor_id,
				vendor: data.vendor,
				vcolor: data.vcolor,
				model: data.model,
				type: data.type,
				sn: data.sn,
				'in': data['in'],
				pusage: data.pusage,
				pstate: data.pstate,
				units: data.units,
				notes: data.notes,
				srvip: ips,
				mgmtip: data.mgmtip,
				color: data.color,
				responsible: data.responsible
			};
			item.id = (mode == 'add') ? result.id : data.id;
			if (callback) callback(item);
		} else {
			Warning('Error during saving of the rack', result.result);
		}
	});
}

ServerCall.prototype.Remove = function(data, callback) {
	console.log(data);
	Confirm('Are you sure to remove server ' + data.name + '?', function() {
		$.getJSON('/call.aspx', { source: 'server', mode: 'remove', id: data.id }, function (result) {
			if (result.result == 'RESULT_OK') {
				if (callback) callback();
			} else {
				Warning('Error during removing of ' + data.name, result.result);
			}
		});
	});
}
